#!/bin/bash

# 定义日志函数
log.warn() { echo -e "[\e[33mWARN\e[0m]:  \e[1m$*\e[0m"; }
log.error() { echo -e "[\e[31mERROR\e[0m]: \e[1m$*\e[0m"; }
log.info() { echo -e "[\e[96mINFO\e[0m]:  \e[1m$*\e[0m"; }
log.debug() { echo -e "[\e[32mDEBUG\e[0m]: \e[1m$*\e[0m"; }

desktop_dir="${HOME}/.local/share/applications/wine/Programs"

find "$desktop_dir" -type f -name "*.desktop" | while read -r desktop_file; do
    log.debug "处理文件: $desktop_file"

    exec_line=$(grep -i '^Exec=' "$desktop_file" | cut -d'=' -f2- | xargs)
    wineprefix=$(echo "$exec_line" | grep -o 'WINEPREFIX=[^ ]*' | cut -d'=' -f2)

    # 核心修复：使用正则表达式提取完整Windows路径
    exe_win_path=$(echo "$exec_line" | grep -o 'C:\\\\.*\.lnk' | head -1)

    log.debug "WINEPREFIX: '$wineprefix'"
    log.debug "原始 Windows 路径: '$exe_win_path'"

    if [[ -z "$wineprefix" || -z "$exe_win_path" ]]; then
        log.warn "参数不完整，跳过"
        continue
    fi

    # 路径转换：处理转义字符和路径分隔符
    exe_win_path_unix=$(printf "%b" "$exe_win_path" | sed -e 's/\\/\//g' -e 's/^[cC]://')
    exe_path_unix="${wineprefix}/dosdevices/c:/${exe_win_path_unix}"

    log.debug "转换后的 UNIX 路径: $exe_path_unix"

    if [[ ! -f "$exe_path_unix" ]]; then
        log.info "文件不存在: $exe_path_unix, 删除 $desktop_file"
        rm "$desktop_file"
    else
        log.debug "文件存在: $exe_path_unix"
    fi
done

rm -vf ${HOME}/.local/share/applications/wine-*